package com.java1234.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.java1234.entity.Answer;
import com.java1234.entity.Question;
import com.java1234.service.AnswerService;
import com.java1234.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.java1234.entity.R;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 答案Controller
 */
@RestController
@RequestMapping("/bsns/subject/answers")
public class AnswerController {
    @Autowired private AnswerService answerService;

    @Autowired private QuestionService questionService;

    /**
     * 查询所有答案信息
     * @return
     */
    @GetMapping("/answerList")
    public R listAll(){
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("answers",answerService.list());
        return R.ok(resultMap);
    }

    /**
     * 根据答案ID查询答案
     * @param ids
     * @return
     */
    @PostMapping("/listByIds")
    public R listByIds(@RequestBody Long[] ids){
        List<Answer> answers=answerService.listByIds(Arrays.asList(ids));
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("answers",answers);
        return R.ok(resultMap);
    }

    /**
     * 根据问题ID查询答案
     * @param questionId
     * @return
     */
    @GetMapping("/listByQuestionId/{questionId}")
    public R listByQuestionId(@PathVariable Long questionId){
        List<Answer> answers=answerService.list(new QueryWrapper<Answer>().eq("question_id",questionId));
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("answers",answers);
        return R.ok(resultMap);
    }

    /**
     * 添加答案
     * @param answer
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody Answer answer){
        boolean isSaved=answerService.save(answer);
        if(isSaved){
            return R.ok("添加成功");
        }else{
            return R.error("添加失败");
        }
    }

    /**
     * 根据ID删除答案信息
     * @param ids
     * @return
     */
    @Transactional
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        answerService.removeByIds(Arrays.asList(ids));
        return R.ok("删除成功");
    }

    /**
     * 更新答案信息
     * @param answer
     * @return
     */
    @PostMapping("/update")
    public R update(@RequestBody Answer answer){
        boolean isUpdated=answerService.updateById(answer);
        if(isUpdated){
            return R.ok("修改成功");
        }else{
            return R.error("修改失败");
        }
    }

}
